package com.open.rbac.service.sys.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import com.open.rbac.model.entity.sys.Menu;


@Transactional(rollbackFor = Exception.class)
public interface MenuRepository extends JpaRepository<Menu, String> {


    List<Menu> findByName(String name);

    @Modifying
    @Query("DELETE FROM menu t1 WHERE t1.id = ?1")
    void deleteReallyById(String id);

    @Query("""
        SELECT DISTINCT t1 FROM menu t1
        INNER JOIN role_menu_rel t2 ON t1.id = t2.menuId
        INNER JOIN role_user_rel t3 ON t2.roleId = t3.roleId
        INNER JOIN user t4 ON t3.userId = t4.id
        AND t4.enable = true
        WHERE t1.enable = true
        AND t3.userId = ?1
        ORDER BY t1.sort, t1.createTime DESC
        """)
    List<Menu> findByUserId(String userId);


    @Query("""
        SELECT DISTINCT t1 FROM menu t1
        INNER JOIN role_menu_rel t2 ON t1.id = t2.menuId
        WHERE t1.enable = true
        AND t2.roleId = ?1
        ORDER BY t1.sort, t1.createTime DESC
        """)
    List<Menu> findByRoleId(String roleId);



    @Modifying
    @Query("UPDATE menu t SET t.enable = ?2 WHERE t.id = ?1")
    void updateEnable(String id, boolean enable);

}
